<template>
  <div>
    <!-- <SearchCusinfo ref="SearchCusinfo" :parentObj="this"></SearchCusinfo> -->

    <a-drawer
      :title="info"
      width="90%"
      :visible="visiblees"
      @close="
        () => {
          if (this.details) {
            this.visible = false
          }
          this.visiblees = false
          this.data2 = []
          this.allList = []
          this.allData = []
        }
      "
      :body-style="{ paddingBottom: '5%' }"
    >
      <a-form-model :rules="rules" ref="ruleForm" :model="entity" v-bind="layout">
        <a-row>
          <a-col :span="8">
            <a-form-model-item label="客户名称:" prop="cusname">
              <a-input v-model="this.cusname" autocomplete="off" :disabled="true" />
            </a-form-model-item>
          </a-col>
          <a-col :span="8">
            <a-form-model-item label="购货方" prop="DicKey">
              <!-- <a-select
                v-if="this.buyPeople.length > 0"
                show-search
                :disabled="details"
                v-model="entity.DicKey"
                placeholder="购货方"
                style="width: 100%"
                :default-active-first-option="false"
                :show-arrow="false"
                :filter-option="false"
                :not-found-content="null"
                @search="handleSearch"
                @change="handleChange">
                <a-select-option v-for="d in buyPeople" :key="d.cCusName">
                  {{ d.cCusName }}
                </a-select-option>
              </a-select> -->
              <a-input v-model="entity.DicKey" disabled></a-input>
              <!-- <a-select v-if="this.buyPeople.length>0"   placeholder="请选择购货方">
                  <a-select-option v-for="item in buyPeople" :key="item" :value="item.Id" >
                    {{ item. }}
                  </a-select-option>
                </a-select> -->
            </a-form-model-item>
          </a-col>
          <a-col :span="8">
            <a-form-model-item label="发票类型" prop="Type">
              <a-select
                show-search
                :disabled="details"
                v-model="entity.Type"
                placeholder="发票类型"
                style="width: 100%"
                @change="TypeChange"
              >
                <a-select-option value="增值税专用发票">增值税专用发票</a-select-option>
                <a-select-option value="增值税普通发票">增值税普通发票</a-select-option>
                <a-select-option value="增值税电子普通发票">增值税电子普通发票</a-select-option>
                <a-select-option value="增值税电子专用发票">增值税电子专用发票</a-select-option>
                <a-select-option value="全电发票(普通发票)">全电发票(普通发票)</a-select-option>
                <a-select-option value="全电发票(专用发票)">全电发票(专用发票)</a-select-option>
              </a-select>
            </a-form-model-item>
          </a-col>
        </a-row>
        <a-row>
          <a-col :span="8">
            <a-form-model-item
              label="税号"
              :prop="
                ['增值税普通发票', '增值税电子普通发票', '全电发票(普通发票)'].includes(entity.Type) ? '' : 'zhanghu'
              "
            >
              <a-input :disabled="details" @input="(e) => {}" v-model="entity.zhanghu" placeholder="税号" />
            </a-form-model-item>
          </a-col>
          <a-col :span="8">
            <a-form-model-item
              label="开户行及账号:"
              :prop="
                ['增值税普通发票', '增值税电子普通发票', '全电发票(普通发票)'].includes(entity.Type) ? '' : 'kaihu'
              "
            >
              <a-input :disabled="details" v-model="entity.kaihu" autocomplete="off" placeholder="请使用空格进行分割" />
            </a-form-model-item>
          </a-col>

          <a-col :span="8">
            <a-form-model-item
              label="地址、电话"
              :prop="
                ['增值税普通发票', '增值税电子普通发票', '全电发票(普通发票)'].includes(entity.Type) ? '' : 'phone'
              "
            >
              <a-input :disabled="details" v-model="entity.phone" autocomplete="off" placeholder="请使用空格进行分割" />
            </a-form-model-item>
          </a-col>
        </a-row>
        <a-row> </a-row>
        <div style="display: flex; justify-content: flex-end">
          <div v-if="!details">
            <a-button style="margin: 0 10px" type="primary" @click="selectDeleteData">货物名称</a-button>
          </div>
          <div v-if="!details">
            <a-button style="margin: 0 10px" type="primary" @click="retainDecimal">保留小数</a-button>
          </div>
          <a-button v-if="!details" style="margin: 0 10px" type="primary" @click="disCountModalShow">折扣</a-button>

          <a-button
            style="margin: 0 10px"
            v-if="!details"
            type="primary"
            @click="
              () => {
                delTaxRateVisibty = true
                delTaxRate = ''
              }
            "
            >税率删除</a-button
          >
          <a-button
            v-if="!details"
            style="margin-right: 10px"
            :disabled="this.selectedRowKeys1.length <= 0"
            type="primary"
            icon="form"
            @click="batchChangePrice"
            >批量改价</a-button
          >
          <a-button
            v-if="!details"
            :disabled="this.selectedRowKeys1.length <= 0"
            type="primary"
            icon="delete"
            @click="batchDeleteData"
            >批量删除</a-button
          >
        </div>
        <div style="padding-bottom: 10%; margin-top: 8px">
          <!-- :dataSource="data2" -->
          <a-table
            ref="table"
            :scroll="{ y: tableHeight, x: tableWidth }"
            :columns="columns0"
            :dataSource="addTableData"
            :pagination="false"
            :rowKey="(row) => row.newUuid"
            :loading="loadingApply"
            :bordered="true"
            :row-selection="details ? null : rowSelection"
            size="small"
          >
            <!-- 标准售价格式化 -->

            <!-- <template slot="origTaxSalePrice" slot-scope="text, record">
              {{ toThousands(record.origTaxSalePrice) || 0 }}
            </template> -->
            <template slot="TaxRate" slot-scope="text, record">
              <!-- {{ text ? text.substr(0, text.length - 1) : '' }} -->
              {{ text }}
            </template>

             <template slot="TM_Name" slot-scope="text, record">
              <CompanySelect v-if="!details && !record.disCountType" style="width: 100%" v-model="record.TM_Name"
                :UnitGroupId="record.ventorycode" :disabled="details" @input="setName($event, record)"
                @select="project($event, record)"></CompanySelect>
              <span v-else>{{ record.TM_Name }}</span>
            </template>
            <template slot="Price" slot-scope="text, record">
              <a-input v-if="!details && !record.disCountType" :disabled="details"
                style="width: 100%; text-align: right" v-model.lazy="record.Price"
                @change="(e) => handlePriceChange(e, record)"></a-input>
              <span v-else>{{ toThousands(record.Price)   }}</span>
            </template>
           <template slot="numskk" slot-scope="text, record, index">
              <a-input v-if="!details && !record.disCountType" :disabled="details"
                style="width: 100%; text-align: right" v-model.lazy="record.numskk" @input="setMon(record)"
                @change="calcAmount(true, record)"></a-input>
              <!-- <span v-else>{{ record.numskk }}</span> -->
            </template>
            <!-- 加成率 -->
            <template slot="markup" slot-scope="text, record, index">
              <template v-if="!details && !record.disCountType">
                <a-input-number :disabled="details" style="width: 80%" v-model.lazy="record.markup"
                  @change="calcAmount"></a-input-number>
              </template>
              <!-- <span v-else>{{ record.markup }}</span> -->
            </template>
             <!--<template slot="kmoneys" slot-scope="text, record, index">
              <span>{{ typeof record.kmoneys == 'string' ? record.kmoneys : (NumberFormats(record.kmoneys)) }}</span>
            </template> -->
            <span slot="action" slot-scope="text, record">
              <template>
                <a v-if="!details" @click="handleDelete([record])">删除</a>
              </template>
            </span>
          </a-table>
        </div>
        <p></p>
        <a-row style="position: fixed; bottom: 5%; z-index: 999999; width: 88%; background-color: #fff">
          <div style="display: flex; justify-content: space-between; align-items: center">
            <a-switch
              v-if="details"
              style="margin-left: 20px"
              disabled
              v-model:checked="IsMerge"
              checked-children="合并相同项"
              un-checked-children="不合并相同项"
            />
            <p style="text-align: right; margin-right: 20px">
              <span>数量合计<span></span> {{ Count || 0.0 }}</span>
              <span style="margin-left: 30px">原价合计<span></span> {{ Amount | NumberFormats }}</span>
              <span style="margin-left: 30px"
                >价税合计<span></span> {{ NumberFormats(Number(Amount) - Number(AmountOld)) || 0 }}</span
              >
              <span style="margin-left: 30px; color: red"
                >折扣额合计 <span v-if="AmountOld != '0.00'">-</span>{{ AmountOld | NumberFormats }}</span
              >
            </p>
          </div>
          <a-col :span="8">
            <a-form-model-item label="收票人:" prop="shoupiaoren">
              <a-input
                :disabled="details"
                v-model="entity.shoupiaoren"
                autocomplete="off"
                placeholder="收票人"
              ></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="8">
            <a-form-model-item label="手机号:" prop="Phone">
              <a-input :disabled="details" v-model="entity.Phone" autocomplete="off" placeholder="收票人手机号" />
            </a-form-model-item>
          </a-col>
          <a-col :span="8">
            <a-form-model-item label="收票地址:" prop="shoupiaodizhi">
              <a-textarea
                :disabled="details"
                v-model="entity.shoupiaodizhi"
                autocomplete="off"
                placeholder="收票地址"
              />
            </a-form-model-item>
          </a-col>
          <a-col :span="8">
            <a-form-model-item label="邮箱地址:" prop="cCusEmail">
              <a-input :disabled="details" v-model="entity.cCusEmail" autocomplete="off" placeholder="邮箱地址" />
            </a-form-model-item>
          </a-col>
          <a-col :span="8">
            <a-form-model-item label="说明:" prop="Remarks">
              <a-input :disabled="details" v-model="entity.Remarks" autocomplete="off" placeholder="说明" />
            </a-form-model-item>
          </a-col>
          <a-col :span="8">
            <a-form-model-item label="备注" prop="Remark">
              <a-textarea :disabled="details" v-model="entity.Remark" autocomplete="off" placeholder="备注" />
            </a-form-model-item>
          </a-col>
        </a-row>
      </a-form-model>
      <div
        :style="{
          position: 'absolute',
          right: 0,
          bottom: 0,
          width: '100%',
          borderTop: '1px solid #e9e9e9',
          padding: '10px 16px',
          background: '#fff',
          textAlign: 'right',
          zIndex: 9999999999,
        }"
      >
        <a-button @click="closeDetails">取消</a-button>
        <a-button v-if="!details" type="primary" @click="SummarySubmission" style="margin-left: 10px">保存</a-button>
      </div>
    </a-drawer>
    <a-modal
      :width="1200"
      style="text-align: center"
      title="货物名称"
      :visible="selectDeleteVisible"
      @ok="handlePushData"
      @cancel="
        () => {
          selectDeleteVisible = false
        }
      "
    >
      <!-- :dataSource="delData" -->
      <a-table
        ref="table"
        :scroll="{ y: tableHeight, x: tableWidth }"
        :columns="columnsPreview"
        :dataSource="delTableData"
        :pagination="false"
        :rowKey="(row, index) => row.newUuid"
        :loading="editLoading"
        :bordered="true"
        :row-selection="rowSelectionDel"
        size="small"
      >
        <template slot="TaxRate" slot-scope="text, record">
          {{ record.TaxRate }}
        </template>
        <template slot="TM_Name" slot-scope="text, record">
          <span>{{ record.TM_Name }}</span>
        </template>
        <template slot="Price" slot-scope="text, record">
          <span>{{ record.Price }}</span>
        </template>
        <template slot="numskk" slot-scope="text, record, index">
          <span>{{ Number(record.numskk).toFixed(4) }}</span>
        </template>
        <template slot="markup" slot-scope="text, record, index">
          <span>{{ record.markup }}</span>
        </template>
        <template slot="kmoneys" slot-scope="text, record, index">
          <span>{{ record.kmoneys }}</span>
        </template>
      </a-table>
    </a-modal>
    <a-modal
      title="批量改价"
      :visible="changeVisible"
      @ok="handleChangePrice"
      @cancel="
        () => {
          this.changeVisible = false
          this.changeMarkup = ''
        }
      "
    >
      <div>
        <span>加成率：</span>
        <a-input-number v-model="changeMarkup"></a-input-number>%
      </div>
    </a-modal>
    <a-modal
      title="请输入折扣金额"
      @ok="disCountOk"
      width="10%"
      :visible="disCountModalVisibly"
      @cancel="
        () => {
          ;(disCount = ''), (disCountModalVisibly = false)
        }
      "
    >
      <div style="display: flex; justify-content: center; align-items: center">
        <a-input placeholder="折扣金额" v-model="disCount"></a-input>
      </div>
    </a-modal>
    <a-modal
      title="保留小数位数"
      @ok="handleRetainDecimal"
      width="10%"
      :visible="retainDecimalVisible"
      @cancel="
        () => {
          retainDecimalVisible = false
        }
      "
    >
      <div style="display: flex; justify-content: center; align-items: center">
        <a-input-number style="width: 200px" :max="8" v-model="retainDecimalCount"></a-input-number>
      </div>
    </a-modal>
    <a-modal
      title="税率删除"
      @ok="delTaxRateFilter"
      width="10%"
      :visible="delTaxRateVisibty"
      @cancel="
        () => {
          delTaxRateVisibty = false
        }
      "
    >
      <a-input style="width: 100px" v-model="delTaxRate" placeholder="税率"></a-input>
    </a-modal>
  </div>
</template>
<script>
  // import {dataList} from './data.js'
import { v4 } from 'uuid'
import {mill2num} from '@/utils/Tools.js'
import SearchCusinfo from './SearchCusinfo'
import moment from 'moment'
import CompanySelect from '@/components/PB/CompanySelect'
import {columnsRead ,columns,columnsPreview,columns2,columns3,SummaryColumns} from './InvoiceApplication.js'
import { invoicemixin } from '@/utils/invoiceApplicationmixin.js'

export default {
  components: {
    SearchCusinfo,
    CompanySelect,
  },
  props: ['back', 'parentObj'],
  data() {
    return {
      columnsRead,
      spinloading: false,
      columnsPreview,
      parentId: '',
      timeDisabled: true,
      editLoading: false,
      delData: [],
      newDelData: [],
      options: [
        {
          value: 0,
          label: '张三',
          address: '地址0',
          phone: '0',
        },
        {
          value: 1,
          label: '李四',
          address: '地址1',
          phone: '1',
        },
        {
          value: 2,
          label: '王五',
          address: '地址2',
          phone: '2',
        },
      ],
      details: false,
      Amount: 0,
      data: [],
      retainDecimalVisible: false,
      retainDecimalCount: 2,
      start: 0,
      SummaryData: [],
      data2: [],
      delTaxRate: '',
      delVentoryname: '',
      allData: [],
      Preview: [],
      selectedRowKeys: [],
      selectedRows: [],
      tableWidth: 0,
      name: '',
      layout: {
        labelCol: { span: 5 },
        wrapperCol: { span: 18 },
      },
      columns3,
      info: '',
      buyPeopleRead: [],
      visiblity: false,
      setTab: '1',
      SummaryColumns,
      changeVisible: false,
      loadingApply: false,
      changeMarkup: '', // 批量修改加成率
      Summary: false,
      pagination: {
        current: 1,
        pageSize: 20,
        onShowSizeChange: (current, pageSize) => (this.pageSize = pageSize),
        showTotal: (total, range) => `总数:${total} 当前:${range[0]}-${range[1]}`,
        pageSizeOptions: ['20', '30', '40', '50', '100'], // 设置pageSize的可选值，页面可以通过下拉框进行选择
        showSizeChanger: true,
      },
      columns0: [],
      pagination2: {
        current: 1,
        pageSize: 20,
        onShowSizeChange: (current, pageSize) => (this.pageSize = pageSize),
        showTotal: (total, range) => `总数:${total} 当前:${range[0]}-${range[1]}`,
        pageSizeOptions: ['20', '30', '40', '50', '100'], // 设置pageSize的可选值，页面可以通过下拉框进行选择
        showSizeChanger: true,
      },
      sorter: { field: 'code', order: 'desc' },
      columns,
      columns2,
      OutboundOrder: '',
      cusid: '',
      time: [],
      buyPeople: [],
      cusname: '',
      queryParam: {
        condition: 'code',
      },
      visible: false,
      visiblees: false,
      loading: false,
      rules: {
        DicKey: [{ required: true, message: '请填写', trigger: 'change' }],
        Type: [{ required: true, message: '请选择发票类型', trigger: 'change' }],
        zhanghu: [
          { required: true, message: '请填写9至20位税号', trigger: 'blur' },
          { min: 9, max: 20, message: '请填写9至20位税号', trigger: 'blur' },
        ],
        kaihu: [{ required: true, message: '请填写', trigger: 'blur' }],
        phone: [{ required: true, message: '请填写', trigger: 'blur' }],
        // Remarks: [{ required: true, message: '请填写', trigger: 'change' }],
        // shoupiaoren: [{ required: true, message: '请填写', trigger: 'change' }],
        // Phone: [{ required: true, message: '请填写', trigger: 'change' }],
        // shoupiaodizhi: [{ required: true, message: '请填写', trigger: 'change' }],
        // beizhu: [{ required: true, message: '请填写', trigger: 'change' }],
      },
      title: '',
      entity: { DicKey: '' },
      flag: true,
      timer: null,
      delTaxRateVisibty: false,
      tableHeight: 0,
      precision: 1e10,
      userInfo: {},
      newArr: [],
      selectedRowKeys1: [],
      cancel: false,
      listData: {},
      AmountOld: 0,
      selectDeleteVisible: false,
      selectedRowKeysDel: [],
      xsList: new Set() /**出库单号*/, //出库单号
      disCountModalVisibly: false,
      disCount: '',
      Amountyuan: 0,
      Count: '0.00', //数量合计
      // 货物名称选中的上数据
      selectRowsArr: {},

      allList: [], // 包含所有货物列表
    }
  },
  watch: {
    allList: {
      handler(e) {
        let addList = this.allList.filter((e) => e.editType === 'add')

        let count = addList
          .map((item) => item.numskk)
          .reduce((accumulator, currentValue) => {
            return Number(accumulator) + Number(currentValue)
          }, 0)
        this.Count = parseFloat(count).toFixed(4) || 0
      },
      deep: true,
    },
  },
  computed: {
    addTableData() {
      return this.allList.filter((item) => item.editType == 'add')
    },
    delTableData() {
      return this.allList.filter((item) => item.editType == 'del')
    },
    // Count() {
    //   let count = 0;
    //   this.data2.forEach(item => {
    //     count += Number(item.numskk)
    //   })
    //   return parseFloat(count).toFixed(4) || 0 ;
    // },
    rowSelectionDel() {
      return {
        selectedRowKeys: this.selectedRowKeysDel,
        onChange: (selectedRowKeys, selectedRows) => {
          this.selectedRowKeysDel = selectedRowKeys
          let arr = []
          this.delData.forEach((item) => {
            this.selectedRowKeysDel.forEach((v) => {
              if (item.newUuid === v) {
                arr.push(item)
              }
            })
          })
          this.selectRowsArr = arr
        },
        getCheckboxProps: (record) => ({
          props: {
            // disabled: record.name === 'Disabled User', // Column configuration not to be checked
            // name: record.name
          },
        }),
      }
    },
    rowSelection() {
      return {
        selectedRowKeys: this.selectedRowKeys1,
        onChange: (selectedRowKeys, selectedRows) => {
          this.selectedRowKeys1 = selectedRowKeys
        },
        getCheckboxProps: (record) => ({
          props: {
            disabled: record.name === 'Disabled User', // Column configuration not to be checked
            name: record.name,
          },
        }),
      }
    },

    rowSelection1() {
      return {
        selectedRowKeys: this.selectedRowKeys,
        onChange: this.onSelectChange,
        // onSelect: this.onSelect,
        // onSelectAll: this.onSelectAll,
        getCheckboxProps: (record) => ({
          props: {
            disabled: record.ApplyTotalQuantity >= record.TotalQuantity, // Column configuration not to be checked
            name: record.name,
          },
        }),
      }
    },
  },
  mounted() {
    // this.$nextTick(() => {
    //   // 页面渲染完成后的回调
    //   this.time = [this.timeFormat(new Date(new Date().getFullYear(), new Date().getMonth(), 1)), this.timeFormat(new Date(new Date().getFullYear(), new Date().getMonth() + 1, 0))]
    // this.tableHeight = document.body.clientHeight - 550
    //   console.log(document.body.clientHeight)
    //   console.log(this.time)
    //   this.getDataList()
    // })
    this.handleResize()
  },
  created() {
    window.addEventListener('resize', this.handleResize);
  },
  destroyed() {
    window.removeEventListener('resize', this.handleResize);
  },
  mixins: [invoicemixin],
  methods: {
    handleResize() {
      try {
        this.tableHeight = document.body.clientHeight - 550
      } catch (error) {
        
      }
    },
    //格式金额，默认保留两位小数，并格式化为千分位
    toThousands(value) {
      if (!value) return '0.00'
     
      return this.NumberFormats(value)
    },
    // 千分位格式化成数值 并且保留几位小数
    convertToNumber(str, num) {
      return mill2num(str, num?num:2)
    },
    NumberFormats(value) {
      if (!value && value != 0) {
        return ''
      }
      // 获取元素的文本内容
      const originalValue = parseFloat( mill2num(value,2))
      // 使用toLocaleString方法将数字格式化为千分位表示
      let res = originalValue.toLocaleString()
      const match = res.match(/\.(\d+)/)
      if (match && match[1].length == 1) {
        // 如果找到匹配小数点后面的数字的长度加0   /'22.4'+0
        return (res += '0')
      } else if ((match && match[1].length == 0) || !match) {
        return (res += '.00')
      } else {
        // 如果没有匹配小数部分长度，返回原数字。
        return res
      }
    },
    // 保留小数
    handleRetainDecimal() {
      this.allList
        .filter((e) => e.editType === 'add')
        .forEach((item) => {
          if (this.selectedRowKeys1.includes(item.newUuid)) {
            item.RetainDecimalCount = this.retainDecimalCount
            // this.handleValChange(null, item, null, true)
            item.Price =
            (item.markup * item.TM_UnitPrice) / 100
              ? ((item.markup * item.TM_UnitPrice) / 100).toFixed(item.RetainDecimalCount || 2)
              : 0
          // item.Price = ((item.markup * item.TM_UnitPrice / 100 * (1 + Number(item.TaxRate.replace('%', '')) / 100))) ? ((item.markup * item.TM_UnitPrice / 100 * (1 + Number(item.TaxRate.replace('%', '')) / 100))).toFixed(8) : 0
       
          }
        })
      this.retainDecimalVisible = false
    },
    retainDecimal() {
      if (this.selectedRowKeys1.length != 1) {
        this.$message.error('请选择一个货品！')
        return
      }
      this.retainDecimalCount =
        this.allList.filter((item) => item.newUuid === this.selectedRowKeys1[0])[0].RetainDecimalCount || 2
      this.retainDecimalVisible = true
    },
    // 折扣点击事件
    disCountModalShow() {
      // console.log('折扣点击事件了', this.selectedRowKeys1)
      if (this.selectedRowKeys1.length != 1) {
        this.$message.error('请选择一个货品！')
        return
      }
      this.disCount = ''
      let flag = false
      let flag1 = false
      this.addTableData.forEach((item) => {
        if (this.selectedRowKeys1.includes(item.newUuid)) {
          flag = mill2num(item.kmoneys) < 0
        }
      })
      if (flag) {
        this.$message.error('该单据为折扣单据')
        return
      }

      this.disCountModalVisibly = true
    },
    // 折扣点击确定
    disCountOk() {
      this.AmountOld = 0

      let arr = JSON.parse(JSON.stringify(this.allList.filter((item) => this.selectedRowKeys1.includes(item.newUuid))))

      if (this.disCount * 1 > arr[0].kmoneys) {
        this.$message.error('折扣价不能大于原价')
        return
      }
      arr.forEach((item) => {
        item.Temp01 = item.newUuid
        item.farter = item.newUuid
        item.newUuid = v4()
        item.kmoneys = this.disCount * -1
        item.specification = ''
        item.compositionQuantity = ''
        item.quantity = ''
        item.origTaxSalePrice = ''
        item.markup = ''
        item.Openedquantity = ''
        item.Price = ''
        item.numskk = ''
        item.TM_Specs = ''
        item.TM_Unit = ''
        item.numskk = ''
        item.Price = ''
        // item.TM_Name = ""
        item.detailcode = item.detailcode + '_' + 1
        item.disCountType = true
      })

      // 折扣替换
      this.allList.forEach((item, index) => {
        if (item.detailcode == arr[0].detailcode) {
          this.allList.splice(index, 1)
        }
      })
      this.allList.push(...arr)

      let seen = {} // 用于存储已经出现的a属性值
      let index = 0 // 用于记录对象的位置
      this.allList.sort(function (obj1, obj2) {
        var a1 = obj1.ventoryname
        var a2 = obj2.ventoryname

        if (!seen.hasOwnProperty(a1)) {
          // 如果a1属性值在seen对象中不存在，则将其添加，并且将index递增
          seen[a1] = index
          index++
        }
        if (!seen.hasOwnProperty(a2)) {
          // 如果a2属性值在seen对象中不存在，则将其添加，并且将index递增
          seen[a2] = index
          index++
        }

        // 根据a属性值在seen对象中的索引来排序
        return seen[a1] - seen[a2]
      })

      this.disCountModalVisibly = false
      this.Amount = 0
      this.AmountOld = 0

      // 计算折扣价格
      this.allList
        .filter((item) => item.editType == 'add')
        .forEach((item) => {
          this.handleValChange(null, item, null, false)
        })
      // 折扣点击确定后初始化选中列表
      this.selectedRowKeys1 = []
    },
    getDecimalPlaces(num, c) {
      let count = c || 2
      const decimalPart = String(num).match(/\.\d*/)
      return (decimalPart ? decimalPart[0].length - 1 : 0) <= count
    },
    async selectDeleteData() {
      this.delData = []
      //  初始化选中数据
      this.selectedRowKeysDel = []
      this.selectDeleteVisible = true
      // await this.getDelData()
    },
    async getDeleteData() {
      this.delData = []
      //  初始化选中数据
      this.selectedRowKeysDel = []
      this.selectDeleteVisible = true
      await this.getDelData()
    },
    // 货物名称弹窗确定
    handlePushData() {
      let arr = []
      this.allList.forEach((item) => {
        if (this.selectedRowKeysDel.includes(item.newUuid)) {
          //  console.log('删除的当前列可以push到最外层数组了', item)
          item.editType = 'add'
        } else {
          arr.push(item)
        }
      })
      this.delData = arr

      // console.log('货物名称点击确定了', this.delData, this.selectedRowKeysDel)
      this.selectDeleteVisible = false

      let count = 0
      this.Amount = 0
      this.AmountOld = 0
      this.allList
        .filter((e) => e.editType == 'add')
        .forEach((item) => {
          item.numskk = Number(item.numskk)
          // 判断是否包含%分号进行追加百分号 为了避免调用税额计算函数出现错误多余渲染百分号的问题
          if (typeof item.TaxRate === 'number') {
            item.TaxRate = item.TaxRate + '%'
          } else if (item.TaxRate === null || item.TaxRate === undefined) {
            item.TaxRate = '0'
          }
          count += item.numskk
          this.handleValChange(null, item, null, false)
        })
      this.Count = parseFloat(count).toFixed(4) || 0
    },
    TypeChange(value) {
      if (value === '增值税普通发票' || value === '增值税电子普通发票' || value === '全电发票(普通发票)') {
        this.$refs.ruleForm.clearValidate(['zhanghu', 'kaihu', 'phone'])
      }
    },
    shouCusinfo() {
      // this.back();
      this.OutboundOrder = ''
      // this.$refs.SearchCusinfo.openForm(null, '选择开票客户')
      this.visible = false
      this.visiblees = false
      this.parentObj.$refs.SearchCusinfo.openForm(null, '选择开票客户')
    },
    openInfo(row) {
      this.visiblees = true
      this.loading = true
      this.selectedRowKeys1 = []
      this.delTaxRate = ''
      this.AmountOld = '0.00'
      this.Count = '0.00'
      this.$http
        .post('/InvoiceManagement/Inv_InvoiceApplyMain/GetInvoicingInformation?id' + '=' + row.Id)
        .then((res) => {
          // res = dataList
          this.loading = false
          if (res.Success) {
            this.delData = []
            this.xsList.clear()
            res.Data.Details.forEach((item) => {
              item.InventoryPrice = this.toThousands(item.InventoryPrice) //金额格式化为千分位
              this.xsList.add(item.OutboundOrder) //出库单号列表
            })

            //  console.log('开始插入了', res.Data.Details)
            this.openForm(row.Id, row.TicketbuyerName, '编辑', row, res.Data)
            
            this.getDelData() //获取删除列表
          } else {
            this.$message.error(res.Msg)
          }
        })
    },
    openForm(id, cCusName, title, userInfo, data, cancel) {
      this.entity = { DicKey: '' }
      this.start = 0
      this.tableWidth = 1580
      this.$nextTick(() => {
        this.tableWidth = 1580
      })

      // this.details = false
      // if (cancel == 'cancel') {
      //   this.cancel = true
      // }
      if (title != '选择出库单') {
        this.Summary = true
        this.$set(this, 'tableWidth', 1520)
        this.$nextTick(() => {
          this.$set(this, 'tableWidth', 1520)
        })
      } else {
        this.Summary = false
      }
      this.userInfo = userInfo
      this.cusname = cCusName

      this.allList.forEach((item) => {
        item.markup = ''
        item.numskk = ''
      })
      this.Amount = 0
      this.name = this.cusname
      // this.columns2.forEach(item=>{

      // })
      this.$http
        .post('/CustomerManagement/CustomerInfo/GetDataListByMySelfAndMoreCondition', {
          PageIndex: 1,
          PageRows: 10000,
          SortField: 'Id',
          SortType: 'desc',
          Search: [{ Condition: 'cCusType', keyword: '1' }, { Condition: 'cCusName' }],
        })
        .then((res) => {

          if (res.Data.length > 0) {
            this.buyPeople = res.Data
            this.buyPeopleRead = res.Data
            // this.entity.DicKey =  res.Data[0].Id  ;
          } else {
            this.name = this.cusname
          }
        })
        .catch((err) => {
          this.$message.error(err)
        })

      this.columns0 = this.columns2
      // let i =this.columns2.findIndex((item)=>item.dataIndex=='compositionQuantity');
      // this.columns2.splice(i,0, { title: '出库数量', dataIndex: 'quantity', width: '20%', align: 'right' },
      //     { title: '已开数量', dataIndex: 'Openedquantity', width: '20%', align: 'right' })
      this.cusid = id
      this.time = [
        this.timeFormat(new Date(new Date().getFullYear(), new Date().getMonth(), 1)),
        this.timeFormat(new Date(new Date().getFullYear(), new Date().getMonth() + 1, 0)),
      ]
      // this.getDataList()
      this.selectedRowKeys = []
      this.selectedRows = []
      this.pagination.current = 1
      this.title = title
      this.handleDetails(data)
    },
    // 删除符合税率/名称
    delTaxRateFilter() {
      // 1、过滤出add
      // 2、相同税率
      // 3、不包含折扣
      // 4、折扣单独删除
      this.allList
        .filter((item) => {
          if(item.editType != 'add'){
            return false
          }
          let text = ''
          if (item.TaxRate && item.TaxRate.replace) {
            text = item.TaxRate.replace('%', '')
          }
          return text == this.delTaxRate && !item.disCountType
        }).forEach(item=>{
          item.editType = 'del'
        })

        let list = this.allList.map((item) => {
          if(item.disCountType){

            let text = ''
            if (item.TaxRate && item.TaxRate.replace) {
              text = item.TaxRate.replace('%', '')
            }
            if(text == this.delTaxRate){
              return ''
            }
          }
            return item
        }).filter(e=>e)
        this.$set(this, 'allList', list)
      


      this.selectedRowKeys1 = []

      this.Amount = 0
      this.AmountOld = 0

      let count = 0
      this.allList
        .filter((e) => e.editType == 'add')
        .forEach((item) => {
          count += Number(item.numskk)
        })
      this.Count = parseFloat(count).toFixed(4) || 0
      this.$emit('input', [...this.allList.filter((e) => e.editType == 'add')])
      this.$forceUpdate()
      this.allList
        .filter((e) => e.editType == 'add')
        .forEach((item) => {
          this.handleValChange(null, item, null, false)
        })
      this.delTaxRateVisibty = false
    },
    handleTableChange(pagination, filters, sorter) {
      this.pagination = { ...pagination }
      this.filters = { ...filters }
      this.sorter = { ...sorter }
      this.getDataList()
      // if (JSON.parse(localStorage.getItem('SELECT_CHECK')) && JSON.parse(localStorage.getItem('SELECT_CHECK')).length > 0) {
      //   this.selectedRowKeys = JSON.parse(localStorage.getItem('SELECT_CHECK'))
      // }
    },
    handleCancel() {
      this.visiblity = false
    },
    changeTime(e) {
      this.timeDisabled = true
      this.time = []
      switch (e) {
        case 0:
          this.time[0] = this.timeFormat(new Date(new Date().getFullYear(), new Date().getMonth(), 1))
          this.time[1] = this.timeFormat(new Date(new Date().getFullYear(), new Date().getMonth() + 1, 0))
          break
        case 1:
          this.time[0] = this.timeFormat(new Date(new Date().getFullYear(), new Date().getMonth() - 2, 1))
          this.time[1] = this.timeFormat(new Date(new Date().getFullYear(), new Date().getMonth() + 1, 0))
          break
        case 2:
          this.time[0] = this.timeFormat(new Date(new Date().getFullYear(), new Date().getMonth() - 5, 1))
          this.time[1] = this.timeFormat(new Date(new Date().getFullYear(), new Date().getMonth() + 1, 0))
          break
        case 3:
          this.timeDisabled = false
          break
      }
    },
    // 保存
    handleOk() {
      let allList = this.allList.filter((e) => e.editType === 'add')
      let flag2 = false
      allList.forEach((item) => {
        if (!this.getDecimalPlaces(item.Price, item.RetainDecimalCount)) {
          flag2 = true
        }
      })
      if (flag2) {
        this.$message.warning('请输入正确的价格，小数位数超过了您设置的上限！')
        return
      }
      const Details = []
      allList.forEach((item) => {
        // let InvoicingAmount =
        Details.push({
          OutboundOrder: item.code,
          InventoryCode: item.ventorycode,
          OutboundOrderDetails: item.detailcode,
          InventoryId: item.idinventory,
          InventoryName: item.ventoryname,
          InventoryPrice: item.origTaxSalePrice,
          Inventoryunit: item.compositionQuantity,
          Inventoryspec: item.specification,
          InvoicingQuantity: item.numskk,
          InvoicingPrice: item.Price,
          InvoicingAmount: mill2num(item.kmoneys),
          InvoicingName: item.TM_Name,
          InvoicingCode: item.Taxproductcode,
          InvoicingId: item.TaxproductId,
          Invoicingunit: item.TM_Unit,
          Invoicingspec: item.TM_Specs,
          TaxRate: item.TaxRate ? Number(item.TaxRate.replace('%', '')) : 0,
          TaxAmount: mill2num(item.TaxPrice),
          Markup: item.markup,
          RetainDecimalCount: item.RetainDecimalCount,
        })
      })

      const obj = {
        Id: this.cusid,
        CusCode: this.userInfo.cCusCode,
        CusId: this.userInfo.Id,
        CusName: this.userInfo.cCusName,
        CusPhone: this.entity.phone,
        CusAddress: this.entity.phone,
        cCusEmail: this.entity.cCusEmail,
        TicketbuyerName: this.entity.DicKey,
        TicketbuyerId: this.entity.DicKey,
        Accbank: this.entity.kaihu,
        TaxRegcode: this.entity.zhanghu,
        PayeeUserId: '1',
        PayeeUserCode: '1',
        PayeeUserName: this.entity.shoupiaoren,
        PayeeUserPhone: this.entity.Phone,
        SellerName: this.entity.SellerName,
        SellerRegcode: this.entity.SellerRegcode,
        SellerAccbank: this.entity.SellerAccbank,
        SellerAddress: this.entity.SellerAddress,
        PayeeUserAddres: this.entity.shoupiaodizhi,
        Memo: this.entity.Remarks,
        Includingtaxinwords: Number(this.Amount) - Number(this.AmountOld),
        Amountincludingtax: Number(this.Amount) - Number(this.AmountOld),
        Remark: this.entity.Remark,
        Type: this.entity.Type,
        IsApply: 0,
        // TicketbuyerName:,//购买方姓名.
        // TicketbuyerId:,//购买方id
        Details,
      }
      // 判断最外层子表是否有数据校验
      if (allList.length == 0) return this.$message.error('货物列表不能为空，请先添加货物')
      // 判断最外层子表是否有开票名称校验
      let isNull = false
      Details.forEach((item) => {
        if (item.InvoicingName === '' || item.InvoicingName == null) {
          isNull = true
        }
      })
      console.log('为啥没校验', allList, isNull)
      // 判断货物数组中是否存在空的名称 如果存在不允许保存
      if (isNull) return this.$message.error('开票使用名称不能存在空值,请先维护开票使用名称')
      console.log('可以继续走了', obj)

      this.$http.post('/InvoiceManagement/Inv_InvoiceApplyMain/UpdateInvoicingData', obj).then((res) => {
        if (res.Success) {
          this.$message.success('提交成功')
          this.visible = false
          localStorage.removeItem('SELECT_CHECK')
          this.visiblity = false
          this.visiblees = false
          this.$parent.$parent.getDataList()
        } else {
          this.$message.error('提交失败')
        }
      })
    },
    onSelectChange(selectedRowKeys, selectedRows) {
      this.selectedRowKeys = selectedRowKeys
      this.selectedRows = selectedRows
    },
    onSelect(record, selected) {
      let select = JSON.parse(localStorage.getItem('SELECT_CHECK'))
      if (selected) {
        this.selectedRowKeys.push(record.OutboundOrder)
      } else {
        // 删除取消选择的
        select = select.filter((item) => item != record.OutboundOrder)
        this.selectedRowKeys = this.selectedRowKeys.filter((item) => item != record.OutboundOrder)
      }
      // 如果选择无数据，就创建一个新的加进去。
      if (!JSON.parse(localStorage.getItem('SELECT_CHECK'))) {
        localStorage.setItem('SELECT_CHECK', JSON.stringify(this.selectedRowKeys))
      } else {
        // 反则push
        select.push(...this.selectedRowKeys)
        localStorage.removeItem('SELECT_CHECK')
        localStorage.setItem('SELECT_CHECK', JSON.stringify([...new Set(select)]))
      }
      this.submitDisabled = this.selectedRowKeys.length <= 0
    },
    onSelectAll(selected, selectedRows, changeRows) {
      const select = JSON.parse(localStorage.getItem('SELECT_CHECK'))
      if (selected) {
        changeRows.forEach((item) => {
          this.selectedRowKeys.push(item.OutboundOrder)
        })
      } else {
        // //删除取消选择的
        changeRows.forEach((item) => {
          select.forEach((item2, index) => {
            if (item2 == item.Id) {
              select.splice(index, 1)
            }
          })
        })
        this.selectedRowKeys = []
      }
      // 如果选择无数据，就创建一个新的加进去。
      if (!JSON.parse(localStorage.getItem('SELECT_CHECK'))) {
        localStorage.setItem('SELECT_CHECK', JSON.stringify(this.selectedRowKeys))
      } else {
        // 反则push
        select.push(...this.selectedRowKeys)
        localStorage.removeItem('SELECT_CHECK')
        localStorage.setItem('SELECT_CHECK', JSON.stringify([...new Set(select)]))
      }
      this.submitDisabled = this.selectedRowKeys.length <= 0
    },
    // 开票信息上一步
    shouorderforgoods() {
      this.OutboundOrder = ''
      this.visiblees = false
      this.time = []
      localStorage.removeItem('SELECT_CHECK')
      this.selectedRowKeys = []
      this.selectedRows = []
      this.visible = true
    },
    handleChangePrice() {
      // 批量修改
      this.Amount = 0
      this.AmountOld = 0

      this.allList
        .filter((e) => e.editType == 'add')
        .forEach((item) => {
          this.selectedRowKeys1.forEach((ite) => {
            if (item.newUuid == ite) {
              item.markup = this.changeMarkup
            }
          })
          this.handleValChange(null, item, null, true)
        })
      this.changeVisible = false
      this.changeMarkup = ''
      this.selectedRowKeys1 = [];
    },
    handleSearch(value) {
      if (value == '') {
        return
      }
      //  this.buyPeople =  this.buyPeople.filter(data => (data.cCusName = data));
      if (this.timer) {
        clearTimeout(this.timer)
      }
      this.timer = setTimeout(() => {
        this.$http
          .post('/CustomerManagement/CustomerInfo/GetDataListByMySelfAndMoreCondition', {
            PageIndex: 1,
            PageRows: 25,
            SortField: 'Id',
            SortType: 'desc',
            Search: [
              { Condition: 'cCusType', keyword: '1' },
              { Condition: 'cCusName', keyword: value },
            ],
          })
          .then((res) => {
            this.buyPeople = res.Data
            this.buyPeopleRead = res.Data

            this.timer = null
          })
          .catch((err) => {
            this.timer = null
            this.$message.error(err)
          })
      }, 500)
    },
    handleChange(value) {
      this.buyPeopleRead.forEach((item) => {
        if (item.cCusName === value) {
          const kaihu = item.cCusBank == null && item.cCusAccount == null
          const phone = item.cCusAddress == null && item.cCusPhone == null
          // this.$set(this.entity, "zhanghu", this.userInfo.cCusTaxnumber)
          // this.$set(this.entity, "kaihu", kaihu ? "" : this.userInfo.cCusBank + this.userInfo.cCusAccount)
          // this.$set(this.entity, "phone", phone ? "" : (this.userInfo.cCusAddress + this.userInfo.cCusPhone))
          // this.$set(this.entity, "cCusEmail", (this.userInfo.cCusEmail))
          this.$set(this.entity, 'zhanghu', item.cCusTaxnumber)
          this.$set(this.entity, 'kaihu', kaihu ? '' : item.cCusBank)
          this.$set(this.entity, 'phone', phone ? '' : item.cCusAddress)
          this.$set(this.entity, 'cCusEmail', item.cCusEmail)
        }
      })
    },
    // throttle(fn, delay) {
    //   let timer = null;
    //   return function () {
    //     let context = this;
    //     let args = arguments;
    //     if (!timer) {
    //       timer = setTimeout(function () {
    //         fn.apply(context, args);
    //         timer = null;
    //       }, delay);
    //     }
    //   }
    // },
    SummarySubmission() {
      this.$refs.ruleForm.validate((valid) => {
        if (valid) {
          if (!['增值税普通发票', '增值税电子普通发票', '全电发票(普通发票)'].includes(this.entity.Type)) {
            if (this.entity.kaihu.split(' ').length !== 2 && this.entity.kaihu != '') {
              this.$message.error('请填充开户行及账号，格式：北京银行 110111111111')
              return
            }
            if (this.entity.phone.split(' ').length !== 2 && this.entity.phone != '') {
              this.$message.error('请填充地址及电话，格式：北京市 13888888888')
              return
            }
          }

          const reg = /^\d+(\.\d{0,8})?$/
          let flag = false
          let flag1 = false
          let flag2 = false
          let flag3
          let flag4 = false
          let allList = this.allList.filter((e) => e.editType == 'add')
          allList.forEach((item) => {
            if (!item.disCountType) {
              if (item.quantity - item.Openedquantity < item.numskk) {
                flag = true
              }
              if (item.numskk === '' || item.TM_Name === '' || item.Price === '') {
                flag1 = true
              }
              if (!this.getDecimalPlaces(item.Price, item.RetainDecimalCount)) {
                flag2 = true
              }

              //出库单号
              if(!item.code){
                flag4 = true
              }
            }
          })
          let isNull = false
          allList.forEach((item) => {
            if (item.TM_Name === '') {
              isNull = true
            } else {
              isNull = false
            }
          })
          // 判断货物数组中是否存在空的名称 如果存在不允许保存
          if (isNull == true) return this.$message.error('开票使用名称不能存在空值,请先维护开票使用名称')

          if (!['增值税普通发票', '增值税电子普通发票', '全电发票(普通发票)'].includes(this.entity.Type)) {
            flag3 = allList.every((item) => {
              return item.TaxRate === allList[0].TaxRate
            })
            if (!flag3) {
              this.$message.warning('请检查列表内每个货物税率是否一致')
              return
            }
          }

          if (flag1) {
            this.$message.warning('信息请填写完毕')
            return
          }
          if (flag2) {
            this.$message.warning('请输入正确的价格，最多八位小数')
            return
          }
          if(flag4){
            this.$message.warning('缺少出库单号！')
            return false
          }
          if (!flag) {
            this.visiblity = true
          } else {
            // this.visiblity = true;
            this.$message.warning('数量不能大于出库-已开')
            return
          }
          // this.name = this.buyPeople.filter(item=>item.Id===this.entity.DicKey)[0].cCusName
          this.newArr = []
          this.Preview = []
          let arr = []
          const obj = {}
          arr = JSON.parse(JSON.stringify(allList))
          arr.forEach((item) => {
            if (!obj[item.TaxproductId]) {
              obj[item.TaxproductId] = []
              obj[item.TaxproductId].push(item)
            } else {
              obj[item.TaxproductId].push(item)
            }
          })
          for (const i in obj) {
            this.Preview.push(...obj[i])
            let OBJ = {}
            obj[i].forEach((item, index) => {
              if (index == 0) {
                OBJ = item
                OBJ.kmoneys = Number(OBJ.kmoneys)
                OBJ.TaxPrice = Number(OBJ.TaxPrice)
              } else {
                OBJ.numskk += item.numskk
                OBJ.kmoneys += Number(item.kmoneys)
                OBJ.TaxPrice += Number(item.TaxPrice)
              }
            })
            // if(Number.isInteger(OBJ.kmoneys)){
            //   console.log(123)
            //   OBJ.kmoneys += '.00';
            // }
            // if (Number.isInteger(OBJ.TaxPrice)) {
            //   OBJ.TaxPrice += '.00';
            // }
            this.newArr.push(OBJ)
          }

          this.handleOk()
          // this.$nextTick(() => {
          //   this.$http.post('/Base_Manage/Base_Seller/GetDataList', {
          //     'PageIndex': 1,
          //     'PageRows': 1,
          //     'SortField': 'Id',
          //     'SortType': 'desc'
          //   }).then(res => {
          //     this.entity.SellerName = res.Data[0].SellerName
          //     this.entity.SellerRegcode = res.Data[0].SellerRegcode
          //     this.entity.SellerAccbank = res.Data[0].SellerAccbank
          //     this.entity.SellerAddress = res.Data[0].SellerAddress
          //     this.$forceUpdate()
          //   }).catch(err => {
          //     this.$message.error(err)
          //   })
          // })
        } else {
          return false
        }
      })
    },
    async project(select, record) {
      record.TaxRate = (select ? select.TM_TaxRate : 0) + '%'

      this.$set(record, 'TM_Name', select ? select.Taxproductname : '')

      record.TaxproductId = select ? select.TaxproductId : ''
      record.Taxproductcode = select ? select.Taxproductcode : ''
      record.TM_Unit = select ? select.TM_Unit : ''

      // await this.handleValChange(null, record, null, true)

      this.Amount = 0
      this.AmountOld = 0

      // 计算折扣价格
      this.allList
        .filter((item) => item.editType == 'add')
        .forEach((item) => {
          this.handleValChange(null, item, null, true)
        })

      
    },
    setName(value, record) {
      record.TM_Name = value
    },
    // setMon(e) {
    //   // e.numskk = e.numskk.replace('.', '',)
    //   //   console.log(e.numskk)
    //   //   if (isNaN(e.numskk * 1)) {
    //   //     e.numskk = "";
    //   //     return;
    //   //   }

    //   const arr = e.numskk.split('.')
    //   if (arr.length > 1) {
    //     e.numskk = arr[0] + '.' + arr[1].slice(0, 2)
    //   }
    //   if (isNaN(e.numskk * 1)) {
    //     e.numskk = ''
    //   }
    //   let count = 0
    //   this.delData = arr
    //   this.Amount = 0
    //   this.AmountOld = 0
    //   this.allList
    //     .filter((e) => e.editType === 'add')
    //     .forEach((item) => {
    //       this.handleValChange(null, item, null, true)
    //       count += Number(item.numskk)
    //     })
    //   this.Count = parseFloat(count).toFixed(4) || 0
    // },
    getDataList() {
      if (!this.cusid) return
      this.selectedRowKeys = []
      this.loading = true
      this.$http
        .post('/InvoiceManagement/ST_RDRecord/GetCustomerRecords', {
          PageIndex: this.pagination.current,
          PageRows: this.pagination.pageSize,
          SortField: 'Time',
          SortType: 'desc',
          Search: {
            Condition: 'CustomerId',
            Keyword: this.cusid,
            Code: this.OutboundOrder,
            StartTime: this.time[0] ? this.timeFormat(this.time[0]) : '',
            EndTime: this.time[1] ? this.timeFormat(this.time[1]) : '',
          },
          ...this.filters,
        })
        .then((resJson) => {
          this.loading = false
          this.data = resJson.Data

          this.allData.push(...new Set(this.data))
          // 清空价格

          if (this.data) {
            this.data.forEach((item) => {
              item.CreateTime = this.timeFormat(item.CreateTime, 'YYYY-MM-DD')
            })
            const pagination = { ...this.pagination }
            pagination.total = resJson.Total
            this.pagination = pagination
          }
        })
    },
    // 批量修改价格
    batchChangePrice() {
      this.changeVisible = true
    },
    //批量删除
    batchDeleteData() {
      /**
       * 1、将标识转为del
         2、如果有 折扣子集 把子集一并删除
         3、清空选中key列表
       */

      this.allList = this.allList
        .map((item) => {
          // 如果有 折扣子集 把子集一并删除
          if (item.farter && this.selectedRowKeys1.includes(item.farter)) {
            return undefined
          }
          // 如果是 折扣 直接删除
          if (item.farter && this.selectedRowKeys1.includes(item.newUuid)) {
            return undefined
          }
          // 将标识转为del
          if (this.selectedRowKeys1.includes(item.newUuid)) {
            item.editType = 'del'
          }
          return item
        })
        .filter((e) => e)
      this.$set(this, 'allList', this.allList)
      // console.log(this.allList, 'list')
      // console.log(list.filter((e) => e))

      // this.$set(
      //   this,
      //   'allList',
      //   list.filter((e) => e)
      // )

      console.log(this.selectedRowKeys1)
      // 批量删除之前  初始化删除后临时存储的数组

    
      // let arr = []
      // this.data2.forEach((item, index) => {
      //   if (this.selectedRowKeys1.includes(item.newUuid)) {
      //   } else {
      //     arr.push(item)
      //   }
      // })
      // this.data2 = arr

      // console.log('开始添加奥deldata数组了-----------------', this.newDelData, this.selectedRowKeys1)

      this.selectedRowKeys1 = []
      this.AmountOld = 0
      this.Amount = 0
      this.allList
        .filter((e) => e.editType === 'add')
        .forEach((item) => {
          this.handleValChange(null, item, null, false)
        })
      // this.selectedRowKeys1 = []
      // let count = 0
      // this.data2.forEach((item) => {
      //   count += Number(item.numskk)
      // })
      // this.Count = parseFloat(count).toFixed(4) || 0

      // this.allList = this.$set(this, 'allList', this.allList)
    },
    // 详情
    handleDetails(data, title) {
      this.listData = data
      let data2 = []
      if (title) {
        this.info = '退票信息'
      } else {
        this.info = '开票信息'
      }
      console.log('编辑')

      this.entity = {}
      this.columns0 = this.columns3
      this.cusname = data.TicketbuyerName

      this.name = data.TicketbuyerName
      this.entity.DicKey = data.TicketbuyerName // 购货方
      this.entity.zhanghu = data.TaxRegcode // 税号
      this.entity.kaihu = data.Accbank // 开户行
      this.entity.phone = data.CusAddress
      this.entity.Remarks = data.Memo
      this.entity.shoupiaoren = data.PayeeUserName
      this.entity.Phone = data.PayeeUserPhone
      this.entity.shoupiaodizhi = data.PayeeUserAddres
      this.entity.Remark = data.Remark
      this.entity.cCusEmail = data.cCusEmail
      this.Amount = data.Amountincludingtax
      this.entity.Type = data.Type

      data.Details.forEach((item) => {
        const obj = {}
        // 插入uuid作对比
        let newUuid = v4()
        obj.newUuid = newUuid
        obj.newUuid = obj.newUuid.replace(/[-]/g, '')
        obj.code = item.OutboundOrder
        obj.detailcode = item.OutboundOrderDetails
        obj.id = item.InventoryId
        obj.ventoryname = item.InventoryName
        obj.origTaxSalePrice = this.convertToNumber(item.InventoryPrice, 2)
        obj.compositionQuantity = item.Inventoryunit
        obj.origTaxSaleAmount = item.umiInvRCost
        obj.specification = item.Inventoryspec
        obj.numskk = item.InvoicingQuantity
        obj.Price = mill2num(item.InvoicingPrice,item.RetainDecimalCount || 2)
        obj.kmoneys = this.$options.filters.NumberFormats(item.InvoicingAmount)
        obj.ventorycode = item.InventoryCode
        obj.TM_Name = item.InvoicingName
        obj.TM_UnitPrice = mill2num(item.InventoryPrice)
        obj.TaxRate = item.TaxRate ? item.TaxRate + '%' : 0 + '%'
        obj.Allkmoneys = mill2num(item.TaxAmount) + mill2num(item.InvoicingAmount)
        obj.TaxPrice = this.convertToNumber(item.TaxAmount, 2)
        obj.markup = item.Markup
        obj.RetainDecimalCount = item.RetainDecimalCount
        obj['editType'] = 'add'
        if(obj.detailcode.includes('_')){//这个时折扣
          obj.disCountType = true
        }
        data2.push(obj)
      })
      data2.forEach(item=>{
        if(item.detailcode.includes('_')){
          let list = item.detailcode.split('_')
          let fatherDetailcode = ''
          if(list.length){
            fatherDetailcode = list[0]
            list = data2.filter(e=>e.detailcode == fatherDetailcode)
            item.farter = list[0].newUuid
          }
        }
      })

      


      this.$set(this, 'allList', data2)

      this.visiblees = true
      this.$set(this, 'tableWidth', 1520)
      this.$nextTick(() => {
        this.$set(this, 'tableWidth', 1520)
        if (this.$refs.ruleForm) {
          this.$refs.ruleForm.clearValidate()
        }
      })

      this.Amount = 0
      data2.forEach((ite) => {
        this.Amount = (
          (this.Amount * this.precision + mill2num(ite.kmoneys)  * this.precision) / this.precision
        ).toFixed(2)
      })
      this.$emit('input', [...this.allList.filter((e) => e.editType === 'add')])
      this.$forceUpdate()
      let count = 0
      data2.forEach((item) => {
        count += Number(item.numskk)
      })
      this.Count = parseFloat(count).toFixed(4) || 0
      this.Amount = 0
      this.AmountOld = 0
      data2.forEach((item) => {
        this.handleValChange(null, item, null, false)
      })
    },
    // 详情取消
    closeDetails() {
      this.details = false
      this.visible = false
      this.visiblees = false
      // this.data2 = []

      // this.$destroy();
      // this.parentObj.Details = false;

      this.columns0 = this.columns2
    },
    // 提交下一步
    handleSubmit() {
      // this.selectedRows = []
      // console.log(this.allData, this.selectedRowKeys)
      // const arr = []
      this.time = []
      this.selectedRowKeys1 = []
      this.OutboundOrder = ''
      // this.allData.forEach(item => {
      //   this.selectedRowKeys.forEach(it => {
      //     if (item.Id == it) {
      //       arr.push(item)
      //     }
      //   })
      // })
      // // 去重
      // this.selectedRows = arr.reduce((accumulator, current) => {
      //   const exists = accumulator.some(item => item.OutboundOrder === current.OutboundOrder)
      //   if (!exists) {
      //     accumulator.push(current)
      //   }
      //   return accumulator
      // }, [])
      if (!this.selectedRows.length) {
        return this.$message.warning('请选择出库单据')
      }
      this.loadingApply = true
      const arr = this.selectedRows.map((item) => {
        return item.Id
      })
      this.visible = false
      this.visiblees = true
      this.$http.post('/InvoiceManagement/ST_RDRecord/GetRdRecordByBillList', arr).then(async (res) => {
        if (!res.Success) {
          this.loadingApply = false
        }
        if (res.Success) {
          this.$set(columns2, 'Price', 0)
          this.entity = res.Data
          this.$set(this.entity, 'DicKey', res.Data.TicketbuyerId)
          this.$http
            .post('/CustomerManagement/CustomerInfo/GetDataListByMySelfAndMoreCondition', {
              PageIndex: 1,
              PageRows: 10000,
              SortField: 'Id',
              SortType: 'desc',
              Search: [{ Condition: 'cCusType', keyword: '1' }, { Condition: 'cCusName' }],
            })
            .then((res) => {
              if (res.Data.length > 0) {
                this.buyPeople = res.Data
                this.buyPeopleRead = res.Data
                this.handleChange(this.entity.DicKey)
                // this.entity.DicKey =  res.Data[0].Id  ;
              }
            })
            .catch((err) => {
              this.$message.error(err)
            })

          for (var item of res.Data.Details) {
            this.$set(item, 'code', item.WsChukuCode)
            this.$set(item, 'detailcode', item.WsChukuDetailId)
            this.$set(item, 'ventorycode', item.cInvCode)
            this.$set(item, 'ventoryname', item.cInvName)

            this.$set(item, 'specification', (item.Batch || '') + '  ' + (item.cInvStd || ''))
            this.$set(item, 'compositionQuantity', item.GroupName)
            this.$set(item, 'quantity', item.Quantity)

            this.$set(item, 'origTaxSaleAmount', item.umiInvRCost)
            // this.$set(item, 'Openedquantity', item.Number || 0)
            this.$set(item, 'Openedquantity', 0)
            this.$set(item, 'ReceivedQuantity', item.nums)

            // 开票名称
            // ---
            this.$set(item, 'origTaxSalePrice', Number(item.InventoryPrice).toFixed(2) || 0)
            this.$set(item, 'markup', 100)
            this.$set(item, 'Price', Number(item.iInvRCost).toFixed(2))
            this.$set(item, 'numskk', item.Quantity)
            this.$set(item, 'kmoneys', item.SumiInvRCost)
            // 原来给的是空 先正确渲染 看后续是否会出现逻辑bug进行修改此处**********
            this.$set(item, 'TaxRate', item.TM_TaxRate)
            // 原来给的是空 先正确渲染 看后续是否会出现逻辑bug进行修改此处**********
            this.$set(item, 'TaxPrice', '')
            this.$set(item, 'TM_Specs', (item.Batch || '') + '  ' + (item.cInvStd || ''))
            // item.markup = 100
            // item.origTaxSalePrice = this.$options.filters.NumberFormats(item.origTaxSalePrice)
            // this.$set(item, 'TM_UnitPrice', item.Price) //替换成原价
            this.$set(item, 'TM_UnitPrice', item.InventoryPrice)

            // mill2num(item.InventoryPrice)

            // item.TM_UnitPrice = item.origTaxSalePrice
            await this.getitemchange(item)
          }

          this.data2 = res.Data.Details

          this.getitemchange(item)
          this.loadingApply = false

          // res.Data.Details.forEach(item => {

          // })
        }
      })
      return

      this.data2 = this.selectedRows
      this.$set(columns2, 'Price', 0)

      this.$nextTick(() => {
        this.loadingApply = true

        const arr = []
        this.data2.forEach((item) => {
          arr.push(item.Id)
        })
        this.$http
          .post('/InvoiceManagement/ST_RDRecord_b/DeliveryNoteReceipt', {
            Search: {
              OutboundOrders: arr,
            },
          })
          .then((res) => {
            this.$http
              .post('/InvoiceManagement/ST_RDRecord_b/GetRDRecordList', {
                PageIndex: 1,
                PageRows: 10000,
                SortField: 'Code',
                SortType: 'desc',
                Search: {
                  OutboundOrders: arr,
                },
              })
              .then((resJson) => {
                const arr = []

                resJson.Data.forEach((item, index) => {
                  arr.push(
                    this.$http
                      .post('/InvoiceManagement/Inv_InvoiceApplyMain/GetRDRecordList', {
                        PageIndex: 1,
                        PageRows: 20,
                        SortField: 'TaxproductId',
                        SortType: 'desc',
                        Search: {
                          Keyword: item.ventorycode,
                        },
                      })
                      .then((resJson) => {
                        item.TaxRate = (resJson.Data[0].TM_TaxRate ? resJson.Data[0].TM_TaxRate : 0) + '%'
                        item.TaxPrice = Number(0).toFixed(2)
                        item.kmoneys = Number(0).toFixed(2)
                        this.$set(item, 'TM_Name', resJson.Data[0].Taxproductname)
                        // item.TM_Name = resJson.Data[0].Taxproductname;
                        item.TaxproductId = resJson.Data[0].TaxproductId
                        item.Taxproductcode = resJson.Data[0].Taxproductcode
                        item.TM_Unit = resJson.Data[0].TM_Unit
                        item.TM_Specs = resJson.Data[0].TM_Specs
                        item.origTaxSalePrice = this.$options.filters.NumberFormats(resJson.Data[0].TM_UnitPrice)
                        item.TM_UnitPrice = resJson.Data[0].TM_UnitPrice
                        item.markup = 100
                        item.numskk = item.Unopenedquantity
                        this.handleValChange(null, item, null, true)
                      })
                      .catch((err) => {
                        // this.$message.error(err)
                      })
                  )
                })

                Promise.all(arr).then(() => {
                  this.loadingApply = false
                  this.data2 = resJson.Data
                  // 清空合计
                  this.Amount = 0
                  // 计算合计
                  this.data2.forEach((ite) => {
                    // 精度console.log(ite)
                    // console.log(this.Amount, Number(ite.kmoneys.replace(/,/g, '')), Number(ite.TaxPrice.replace(/,/g, '')))
                    this.Amount = ((this.Amount * this.precision + mill2num(ite.kmoneys) * this.precision) / this.precision).toFixed(2)
                    // this.Amount = this.Amount  + Number(ite.kmoneys.replace(',', '')) + Number(ite.TaxPrice.replace(',', '')) ;
                  })

                  this.$forceUpdate()
                })
              })
          })
      })

      this.$nextTick(() => {
        this.$refs.ruleForm.clearValidate()

        const kaihu = this.userInfo.cCusBank == null && this.userInfo.cCusAccount == null
        const phone = this.userInfo.cCusAddress == null && this.userInfo.cCusPhone == null
        this.$set(this.entity, 'DicKey', this.userInfo.cCusName)
        this.$set(this.entity, 'zhanghu', this.userInfo.cCusTaxnumber)
        this.$set(this.entity, 'kaihu', kaihu ? '' : this.userInfo.cCusBank + this.userInfo.cCusAccount)
        this.$set(this.entity, 'phone', phone ? '' : this.userInfo.cCusAddress + this.userInfo.cCusPhone)
        this.$set(this.entity, 'cCusEmail', this.userInfo.cCusEmail)
      })
    },
    handleDelete(items) {
      var thisObj = this
      this.$confirm('确认删除吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }).then(() => {
        return new Promise((resolve, reject) => {
          items.forEach((element) => {
            var index = thisObj.data2.indexOf(element)
            thisObj.data2.splice(index, 1)
            var keyIndex = thisObj.selectedRowKeys.indexOf(element.code)
            thisObj.selectedRowKeys.splice(keyIndex, 1)
          })
          this.Amount = 0
          this.data2.forEach((ite) => {
            this.Amount = ((this.Amount * this.precision + mill2num(ite.kmoneys) * this.precision) / this.precision).toFixed(2)
          })
          thisObj.$emit('input', [...thisObj.data2])
          resolve()
        })
      })
    },
    // 价格框输入
    handlePriceChange(val, item) {
      // const reg = /^\d+(\.\d{0,2})?$/
      if (this.getDecimalPlaces(item.Price, item.RetainDecimalCount)) {
        // item.Price = Number(val.target.value)
      } else {
        this.$message.warning(
          '请输入正确的价格，最多' + (item.RetainDecimalCount ? item.RetainDecimalCount : 2) + '位小数'
        )
        return
      }
      item.markup =
        (Number(val.target.value) / item.TM_UnitPrice) * 100
          ? ((Number(val.target.value) / item.TM_UnitPrice) * 100).toFixed(4)
          : 0
      // item.markup = ((Number(val.target.value) - this.$options.filters.NumberFormats(item.Price / (1 + item.TaxRate.replace('%', '') / 100) * item.TaxRate.replace('%', '') / 100)) / item.TM_UnitPrice * 100) ? ((Number(val.target.value) - this.$options.filters.NumberFormats(item.Price / (1 + item.TaxRate.replace('%', '') / 100) * item.TaxRate.replace('%', '') / 100)) / item.TM_UnitPrice * 100).toFixed(4) : 0
      this.calcAmount(false)
      item.Price = val.target.value

      // this.handleValChange(null, item)
    },
    // 精度丢失计算
    actionOperationResult(val1, val2, val3) {
      const p = this.actionOperation(val1, val2, val3)
      return (val1 * p * (val2 * p) * (val3 * p || 1)) / (p * p * (val3 ? p : 1))
    },
    actionOperation(val1, val2, val3) {
      const len1 = val1.toString().length - val1.toString().indexOf('.') - 1
      const len2 = val2.toString().length - val2.toString().indexOf('.') - 1
      let p = 0
      if (val3) {
        const len3 = val3.toString().length - val3.toString().indexOf('.') - 1
        p = Math.max(len1, len2, len3)
      } else {
        p = Math.max(len1, len2)
      }

      // 避免最终求出结果的长度大于最大长度的时候导致精度丢失 开启下面
      // p += p - Math.min(len1, len2);
      return Math.pow(10, p)
    },
    calcAmount(editPrice, item) {
      item && this.setMon(item)
      this.Amount = 0
      this.AmountOld = 0
      this.allList.filter(e=>e.editType ==='add').forEach((item) => {
        this.handleValChange(null, item, null, editPrice||false)
      })
    },
    async handleValChange(val, item, index, f) {
      let kmoneys = 0
      if (item.Price && item.numskk) {
        // if ((item.numskk + '').split('.').length > 1) {
        //   if ((item.numskk + '').split('.')[1].length > 2) {
        //     return
        //   }
        // }
        if (item.markup < 0) {
          item.markup = 0
        }
        
        if (item.numskk < 0) {
          item.numskk = 0
        }
        if (f) {
          item.Price =
            (item.markup * item.TM_UnitPrice) / 100
              ? ((item.markup * item.TM_UnitPrice) / 100).toFixed(item.RetainDecimalCount || 2)
              : 0
          // item.Price = ((item.markup * item.TM_UnitPrice / 100 * (1 + Number(item.TaxRate.replace('%', '')) / 100))) ? ((item.markup * item.TM_UnitPrice / 100 * (1 + Number(item.TaxRate.replace('%', '')) / 100))).toFixed(8) : 0
          item.cleanPrice =
            ((item.markup * item.TM_UnitPrice) / 100) * (Number(item.TaxRate.replace('%', '')) / 100)
              ? (((item.markup * item.TM_UnitPrice) / 100) * (Number(item.TaxRate.replace('%', '')) / 100)).toFixed(8)
              : 0
        }

        let cleanPrice = 0
        // 计算金额
        if (item.Price && Number(item.numskk)) {
          kmoneys = this.actionOperationResult(item.Price, Number(item.numskk)).toFixed(2)
          cleanPrice = this.actionOperationResult(item.Price, Number(item.numskk)).toFixed(2)
        }
      } else {
        kmoneys = mill2num(item.kmoneys)
        // kmoneys = item.kmoneys;
      }
      item.kmoneys = this.$options.filters.NumberFormats(kmoneys)
      // 计算税额 这个判断临时改成计算的了
      if (kmoneys && !item.disCountType) {
        // item.TaxPrice = this.toThousands(item.TaxPrice) 之前用的这个

        const TaxRate = Number(item.TaxRate.replace('%', ''))

        item.TaxPrice = (this.convertToNumber(item.kmoneys) / (1 + TaxRate)) * TaxRate
        
        item.TaxPrice = mill2num(item.TaxPrice,2)
      } else {
     
        const TaxRate = Number(item.TaxRate.replace('%', ''))

        item.TaxPrice = (this.convertToNumber(item.kmoneys) / (1 + TaxRate)) * TaxRate
        
        item.TaxPrice = mill2num(item.TaxPrice,2)
      }
      let numKmoneys = mill2num(item.kmoneys)
      //折扣额合计
      if (numKmoneys < 0) {
        this.AmountOld -= mill2num(item.kmoneys) * 1
      }
      // 不可跟上边这句换位置
      numKmoneys = numKmoneys > 0 ? numKmoneys : 0;// 这句用于放大计算

      item.kmoneys = item.kmoneys + ''
      this.Amount = ((this.Amount * this.precision + numKmoneys * this.precision) / this.precision).toFixed(2)

      this.Amountyuan = this.Amount - this.AmountOld
   
      this.$emit('input', [...this.allList.filter((e) => e.editType === 'add')])
      this.$forceUpdate()
    },
    callback(e) {
      this.setTab = e
      if (e == '1') {
      } else {
        this.$http
          .post('/InvoiceManagement/v_applicationsummary/GetDataList', {
            PageIndex: 1,
            PageRows: 10000,
            SortField: 'code',
            SortType: 'desc',
            Search: {
              Condition: 'ParentId',
              Keyword: this.parentId,
            },
          })
          .then((res) => {
            res.Data.forEach((item) => {
              // item.InvoicingPrice=this.$options.filters.NumberFormatss(item.InvoicingPrice)
              item.InvoicingAmount = this.$options.filters.NumberFormats(item.InvoicingAmount)
              item.TaxAmount = this.$options.filters.NumberFormats(item.TaxAmount)
              item.InvoicingQuantity = this.$options.filters.NumberFormat(item.InvoicingQuantity)
            })
            this.SummaryData = res.Data
            // data.Details.forEach(item => {
            //     let obj = {};
            //     obj.code = item.OutboundOrder;
            //     obj.detailcode = item.OutboundOrderDetails;
            //     obj.id = item.InventoryId;
            //     obj.ventoryname = item.InventoryName;
            //     obj.origTaxSalePrice = this.$options.filters.NumberFormats(item.InventoryPrice);
            //     obj.compositionQuantity = item.Inventoryunit;
            //     obj.specification = item.Inventoryspec;
            //     obj.numskk = item.InvoicingQuantity;
            //     obj.Price = this.$options.filters.NumberFormatss(item.InvoicingPrice);
            //     obj.kmoneys = this.$options.filters.NumberFormats(item.InvoicingAmount);
            //     obj.ventorycode = item.InventoryCode;
            //     obj.TM_Name = item.InvoicingName;
            //     obj.TaxRate = item.TaxRate ? item.TaxRate + '%' : 0 + '%';
            //     obj.Allkmoneys = Number(item.TaxAmount) + Number(item.InvoicingAmount);
            //     obj.TaxPrice = this.$options.filters.NumberFormats(item.TaxAmount);
            //     obj.markup = item.Markup;
            //     this.data2.push(obj);
            //   })
          })
      }
    },
    async getitemchange(item) {
      await this.$http
        .post('/InvoiceManagement/Inv_InvoiceApplyMain/GetRDRecordList', {
          PageIndex: 1,
          PageRows: 20,
          SortField: 'TaxproductId',
          SortType: 'desc',
          Search: {
            Keyword: item.ventorycode,
          },
        })
        .then(async (resJson) => {
          item.TaxRate = (resJson.Data[0] ? resJson.Data[0].TM_TaxRate : 0) + '%'
          // item.TaxPrice = Number(0).toFixed(2)
          // item.kmoneys = Number(0).toFixed(2)
          this.$set(item, 'TM_Name', resJson.Data[0] ? resJson.Data[0].Taxproductname : '')
          // item.TM_Name = resJson.Data[0].Taxproductname;
          item.TaxproductId = resJson.Data[0] ? resJson.Data[0].TaxproductId : ''
          item.Taxproductcode = resJson.Data[0] ? resJson.Data[0].Taxproductcode : ''
          item.TM_Unit = resJson.Data[0] ? resJson.Data[0].TM_Unit : ''
          // item.TM_Specs = resJson.Data[0].TM_Specs
          // item.origTaxSalePrice = this.$options.filters.NumberFormats(item.origTaxSalePrice)
          // item.origTaxSalePrice = this.$options.filters.NumberFormats(item.origTaxSalePrice)
          // item.TM_UnitPrice = item.origTaxSalePrice
          // item.markup = 100
          // item.numskk = item.Quantity
          await this.handleValChange(null, item, null, true)
        })
    },
    timeFormat(val) {
      // 时间格式化函数
      return moment(val).format('YYYY-MM-DD')
    },

    async getDelData() {
      this.editLoading = true
      await this.$http
        .post('/InvoiceManagement/ST_RDRecord/GetBillListCalc', Array.from(this.xsList))
        .then(async (res) => {
          if (res.Success) {
            this.$set(columns2, 'Price', 0)
            for (var item of res.Data) {
              this.$set(item, 'code', item.WsChukuCode)
              this.$set(item, 'detailcode', item.WsChukuDetailId)
              this.$set(item, 'ventorycode', item.cInvCode)
              this.$set(item, 'ventoryname', item.cInvName)

              this.$set(item, 'specification', (item.Batch || '') + '  ' + (item.cInvStd || ''))
              this.$set(item, 'compositionQuantity', item.GroupName)
              this.$set(item, 'quantity', Number(item.Quantity).toFixed(4) || 0)

              this.$set(item, 'origTaxSaleAmount', item.umiInvRCost)
              // this.$set(item, 'Openedquantity', item.Number || 0)
              this.$set(item, 'Openedquantity', 0)
              this.$set(item, 'ReceivedQuantity', item.nums)

              // 开票名称
              // ---
              this.$set(item, 'origTaxSalePrice', this.toThousands(item.InventoryPrice))
              this.$set(item, 'markup', 100)
              let iInvRCost = Number(item.iInvRCost)

              this.$set(item, 'Price', Number(item.iInvRCost).toFixed(2))
              this.$set(item, 'numskk', item.Quantity)
              this.$set(item, 'kmoneys', this.toThousands(item.SumiInvRCost))
              // 原来给的是空。先正确渲染 后续有问题修改此处************
              this.$set(item, 'TaxRate', item.TM_TaxRate)
              // 原来给的是空。先正确渲染 后续有问题修改此处************
              // 含税金额
              let newSumiInvRCost = Number(item.SumiInvRCost)
              // //  计算税额 公式=含税金额/(1+税率)*税率
              let TaxPrice = (newSumiInvRCost / (1 + item.TM_TaxRate)) * item.TM_TaxRate
              this.$set(item, 'TaxPrice', this.toThousands(TaxPrice))
              this.$set(item, 'TM_Specs', (item.Batch || '') + '  ' + (item.cInvStd || ''))
              // item.markup = 100
              // item.origTaxSalePrice = this.$options.filters.NumberFormats(item.origTaxSalePrice)
              // this.$set(item, 'TM_UnitPrice', item.Price) //替换成原价
              this.$set(item, 'TM_UnitPrice', item.InventoryPrice)
              this.$set(item, 'editType', 'del')

              // item.TM_UnitPrice = item.origTaxSalePrice
              // await this.getitemchange(item)
            }
            let newArr = []
            let ventorycodeList = this.allList.map(res=>res.ventorycode)

            res.Data.forEach((item) => {
              let newUuid = v4()
              item['newUuid'] = newUuid
              item.newUuid = item.newUuid.replace(/[-]/g, '')

              if(!ventorycodeList.includes(item.ventorycode)){
                newArr.push(item)
              }
            })
            this.$set(this, 'allList', [...this.allList, ...newArr])
            this.delData = newArr
          }
        })
        .finally(() => {
          this.editLoading = false
        })
    },
  },
}
</script>
<style scoped>
/deep/
  .ant-table-small
  > .ant-table-content
  > .ant-table-scroll
  > .ant-table-header
  > table
  > .ant-table-thead
  > tr
  > th {
  text-align: center !important;
}
</style>
